import { DataTypes, Model, Op } from 'sequelize';
import sequelize from '../utils/database';

export interface BannerAttributes {
  id?: number;
  title: string;
  image: string;
  linkUrl?: string;
  sortOrder?: number;
  position?: 1 | 2; // 1-首页顶部，2-首页中部
  startTime: Date;
  endTime: Date;
  status?: 0 | 1; // 0-禁用，1-启用
  createdAt?: Date;
  updatedAt?: Date;
}

export class Banner extends Model<BannerAttributes> implements BannerAttributes {
  public id!: number;
  public title!: string;
  public image!: string;
  public linkUrl?: string;
  public sortOrder!: number;
  public position!: 1 | 2;
  public startTime!: Date;
  public endTime!: Date;
  public status!: 0 | 1;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  /**
   * 检查轮播图是否在有效期内
   */
  public isActive(): boolean {
    const now = new Date();
    return this.status === 1 && 
           this.startTime <= now && 
           this.endTime >= now;
  }

  /**
   * 获取位置描述
   */
  public getPositionText(): string {
    return this.position === 1 ? '首页顶部' : '首页中部';
  }

  /**
   * 获取状态描述
   */
  public getStatusText(): string {
    return this.status === 1 ? '启用' : '禁用';
  }
}

Banner.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: '轮播图ID',
    },
    title: {
      type: DataTypes.STRING(200),
      allowNull: false,
      comment: '标题',
      validate: {
        notEmpty: {
          msg: '标题不能为空',
        },
        len: {
          args: [1, 200],
          msg: '标题长度必须在1-200个字符之间',
        },
      },
    },
    image: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '图片URL',
      validate: {
        notEmpty: {
          msg: '图片URL不能为空',
        },
        isValidImageUrl(value: string) {
          // 允许完整URL或相对路径
          const urlPattern = /^https?:\/\/.+/;
          const pathPattern = /^\/uploads\/.+/;
          if (!urlPattern.test(value) && !pathPattern.test(value)) {
            throw new Error('请输入有效的图片URL或路径');
          }
        },
      },
    },
    linkUrl: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '链接地址',
      field: 'link_url',
      validate: {
        isValidLinkUrl(value: string | null) {
          // 允许空值、null或空字符串
          if (!value || value.trim() === '') {
            return;
          }
          // 只有当有值时才验证URL格式
          const urlPattern = /^https?:\/\/.+/;
          if (!urlPattern.test(value)) {
            throw new Error('请输入有效的链接地址（以http://或https://开头）');
          }
        },
      },
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '排序',
      field: 'sort_order',
      validate: {
        min: {
          args: [0],
          msg: '排序值不能小于0',
        },
      },
    },
    position: {
      type: DataTypes.TINYINT,
      defaultValue: 1,
      comment: '位置：1-首页顶部，2-首页中部',
      validate: {
        isIn: {
          args: [[1, 2]],
          msg: '位置值必须是1或2',
        },
      },
    },
    startTime: {
      type: DataTypes.DATE,
      allowNull: false,
      comment: '开始时间',
      field: 'start_time',
      validate: {
        notNull: {
          msg: '开始时间不能为空',
        },
        isDate: {
          msg: '请输入有效的开始时间',
          args: true,
        },
      },
    },
    endTime: {
      type: DataTypes.DATE,
      allowNull: false,
      comment: '结束时间',
      field: 'end_time',
      validate: {
        notNull: {
          msg: '结束时间不能为空',
        },
        isDate: {
          msg: '请输入有效的结束时间',
          args: true,
        },
        isAfterStartTime(value: Date) {
          if (this.startTime && value <= this.startTime) {
            throw new Error('结束时间必须晚于开始时间');
          }
        },
      },
    },
    status: {
      type: DataTypes.TINYINT,
      defaultValue: 1,
      comment: '状态：0-禁用，1-启用',
      validate: {
        isIn: {
          args: [[0, 1]],
          msg: '状态值必须是0或1',
        },
      },
    },
  },
  {
    sequelize,
    modelName: 'Banner',
    tableName: 'banners',
    timestamps: true,
    underscored: true,
    indexes: [
      {
        fields: ['position'],
      },
      {
        fields: ['status'],
      },
      {
        fields: ['start_time', 'end_time'],
      },
      {
        fields: ['sort_order'],
      },
    ],
    scopes: {
      // 只获取启用的轮播图
      active: {
        where: {
          status: 1,
        },
      },
      // 获取当前有效的轮播图
      current: {
        where: {
          status: 1,
          startTime: {
            [Op.lte]: new Date(),
          },
          endTime: {
            [Op.gte]: new Date(),
          },
        },
      },
      // 按位置获取
      byPosition: (position: number) => ({
        where: {
          position,
        },
      }),
    },
  }
);

export default Banner;